package com.ljyanimo.controller;

import com.ljyanimo.constant.AnimoConstant;
import com.ljyanimo.constant.AuthConstant;
import com.ljyanimo.response.ServerResponse;
import com.ljyanimo.vo.LoginUserVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 登录相关
 * @author Animo
 * @Date 2020/9/29
 * @Blog http://www.ljyanimo.com
 */
@Controller
public class LoginController {

    /**
     * 登录页面  如果要使用记住我的话  则需要把权限设置为user 这样的话才能通过记住我进入此页面。
     * 如果是authc的话则关闭浏览器在访问的话需要登录
     * @return
     */
    @GetMapping("/login")
    public String login(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isRemembered() || subject.isAuthenticated()){
            return "redirect:/";
        }
        return "login";
    }


    @PostMapping(AuthConstant.NOAD + "/login")
    @ResponseBody
    public ServerResponse login(@RequestBody LoginUserVo loginUserVo){

        boolean flag = Boolean.FALSE;

        if(loginUserVo.getRememberMe()!=null && loginUserVo.getRememberMe().equals(AnimoConstant.DEFAULT_REMEMBERME)){
            flag = Boolean.TRUE;
        }

        /**
         * TODO 需要校验参数
         */
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginUserVo.getAccount(),loginUserVo.getPassword(),flag);
        try {
            SecurityUtils.getSubject().login(usernamePasswordToken);
        }catch (IncorrectCredentialsException e){
            return ServerResponse.createByError("账号或密码错误");
        }catch (UnknownAccountException e){
            return ServerResponse.createByError(e.getMessage());
        }catch (DisabledAccountException e){
            return ServerResponse.createByError(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }

    @PostMapping("/logout")
    @ResponseBody
    public ServerResponse logout(){
        SecurityUtils.getSubject().logout();
        return ServerResponse.createBySuccess("正在跳转......");
    }

}
